<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Files;


use Selibra\Command\CommandHelper;
use Selibra\Tools\Console;

class Ignore
{
    /**
     * @var array
     */
    protected array $ignores = [];


    /**
     * 命令行处理
     * @var array
     */
    protected static array $cliIgnoreDir = [];


    /**
     * @param string $ignoreFile
     */
    public function add(string $ignoreFile)
    {
        $this->ignores[$ignoreFile] = true;
    }


    /**
     * @param string $ignoreFile
     */
    public function remove(string $ignoreFile)
    {
        unset($this->ignores[$ignoreFile]);
    }


    /**
     * @param $ignoreFile
     * @return bool
     */
    public function exist($ignoreFile)
    {
        if (array_key_exists($ignoreFile, $this->ignores) || in_array($ignoreFile, self::getCliIgnoreDir())) {
            return true;
        }
        if (is_dir($ignoreFile) && is_file($ignoreFile . '/' . '.selibraignore')) {
            // 获取文件内容
            $selibraIgnore = file_get_contents($ignoreFile . DIRECTORY_SEPARATOR . '.selibraignore');
            if (!empty($selibraIgnore)) {
                // 获取当前命令名称
                $selibraIgnoreArray = preg_split('(\r\n|\n|\r)', $selibraIgnore);
                if (!in_array(CommandHelper::getCommandName(), $selibraIgnoreArray)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }


    /**
     * @return array
     */
    public function getIgnores()
    {
        return array_keys($this->ignores);
    }


    /**
     * @return array
     */
    protected static function getCliIgnoreDir()
    {
        if (empty(self::$cliIgnoreDir)) {
            foreach ($GLOBALS['argv'] as $key => $argvItem) {
                if (strpos($argvItem, '--ignore-dir=') === 0) {
                    $cliignoreDir = explode(',', str_replace('--ignore-dir=', '', $argvItem));
                    foreach ($cliignoreDir as $item) {
                        self::$cliIgnoreDir[] = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, Config::getRootPath() . DIRECTORY_SEPARATOR . $item);
                    }
                    break;
                }
            }
        }
        return self::$cliIgnoreDir;
    }

}